package com.qiguliuxing.dts.db.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiguliuxing.dts.db.dao.DtsKeywordMapper;
import com.qiguliuxing.dts.db.domain.DtsKeyword;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DtsKeywordService {
	@Resource
	private DtsKeywordMapper keywordsMapper;

	public DtsKeyword queryDefault() {
		QueryWrapper<DtsKeyword> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsKeyword::getIsDefault, true);
		queryWrapper.lambda().eq(DtsKeyword::getDeleted, false);
		return keywordsMapper.selectOne(queryWrapper);
	}

	public List<DtsKeyword> queryHots() {
		QueryWrapper<DtsKeyword> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(DtsKeyword::getIsHot, true);
		queryWrapper.lambda().eq(DtsKeyword::getDeleted, false);
		return keywordsMapper.selectList(queryWrapper);
	}

	public List<DtsKeyword> queryByKeyword(String keyword, Integer page, Integer size) {
		QueryWrapper<DtsKeyword> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().like(DtsKeyword::getKeyword, keyword);
		queryWrapper.lambda().eq(DtsKeyword::getDeleted, false);
		IPage<DtsKeyword> iPage = new Page<>(page, size);
		return keywordsMapper.selectPage(iPage, queryWrapper).getRecords();
//		example.setDistinct(true);
		//TODO,distinct待完善
	}

	public List<DtsKeyword> querySelective(String keyword, String url, Integer page, Integer limit, String sort,
			String order) {
		QueryWrapper<DtsKeyword> queryWrapper = new QueryWrapper<>();
		if (StrUtil.isNotEmpty(keyword)) {
			queryWrapper.lambda().like(DtsKeyword::getKeyword, keyword);
		}
		if (StrUtil.isNotEmpty(url)) {
			queryWrapper.lambda().like(DtsKeyword::getUrl, url);
		}
		queryWrapper.lambda().eq(DtsKeyword::getDeleted, false);
		if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)) {
			queryWrapper.orderByDesc(sort);
		}
		IPage<DtsKeyword> iPage = new Page<>(page, limit);
		return keywordsMapper.selectPage(iPage, queryWrapper).getRecords();
	}

	public void add(DtsKeyword keywords) {
		keywords.setAddTime(LocalDateTime.now());
		keywords.setUpdateTime(LocalDateTime.now());
		keywordsMapper.insert(keywords);
	}

	public DtsKeyword findById(Integer id) {
		return keywordsMapper.selectById(id);
	}

	public int updateById(DtsKeyword keywords) {
		keywords.setUpdateTime(LocalDateTime.now());
		return keywordsMapper.updateById(keywords);
	}

	public void deleteById(Integer id) {
		keywordsMapper.deleteById(id);
	}
}
